package eleanor.ltd.isRealEstate.pages.client;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;

import eleanor.ltd.isRealEstate.dao.client.ClientDAO;
import eleanor.ltd.isRealEstate.dao.user.UserDAO;
import eleanor.ltd.isRealEstate.entities.client.Client;
import eleanor.ltd.isRealEstate.entities.user.User;
import eleanor.ltd.isRealEstate.model.glov.GenericSelectModel;
import eleanor.ltd.isRealEstate.pages.Index;

public class AddClient {

	@Property
	@SessionState(create = false)
	private Client client;
	
	@Inject
	private ClientDAO clientDAO;
	
	@Property
	private User user;
	
	@Inject
	private UserDAO userDAO;
	
	private GenericSelectModel<User> users;
	
	@Inject
	private PropertyAccess access;
	
	@Component
	private Form addClientForm;
	
	void onPrepare() {
		client = new Client();
	}

	public GenericSelectModel<User> getUsers() {
		users = new GenericSelectModel<User>(userDAO.findAll(), User.class, "username", "id", access);
		return users;
	}
	
	@Log
	Object onSubmitFromAddClientForm() {
		if(clientDAO.findByUserID(user.getId()).size() == 0) {
			client.setName(client.getName());
			client.setSurname(client.getSurname());
			client.setAddress(client.getAddress());
			client.setClientEmail(client.getClientEmail());
			client.setPhoneOne(client.getPhoneOne());
			if(client.getPhoneTwo() != null) {
				client.setPhoneTwo(client.getPhoneTwo());
			}
//			client.setUserID(client.getUserID());
			clientDAO.save(client);
			return Index.class;
		} else {
			return AddClient.class;
		}
		
	}
	
}
